<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\helper\Time;
use think\Db;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class QuesGraduate extends Ques
{

    /**
     * QuesStudent模型对象
     * @var \app\admin\model\QuesStudent
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\QuesStudent;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {

        $whereQues = [];
        $whereStu = [];


        if(isset($this -> sess['studentIds'])){
            $whereQues['student_id'] = ['in',$this -> sess['studentIds']];
            $whereStu['id'] = ['in',$this -> sess['studentIds']];
        }

        if (input('?title') && input('?answer'))
        {
            $title = input('title');
            $answer =  input('answer');
            $whereQues[$title] = $answer;
        }

        $whereRep = [];
        $groups = $this -> auth -> getGroupIds();
        if(in_array(6,$groups)){
            $filter = json_decode(input('filter'),true);
            if($filter['update_time']){
                $timeArr = explode(' - ',$filter['update_time']);
                if(isset($timeArr[1])){
                    $timeArr = [
                        strtotime($timeArr[0]),strtotime($timeArr[1])
                    ];
                }else{
                    $timeArr = Time::today();
                }
            }else{
                $timeArr = Time::today();
            }
            $college_ids = (new \app\admin\model\CollegeReport) -> where('type',3) -> whereBetween('create_time',$timeArr) -> column('college_id');

            $whereRep['college_id'] = ['in',$college_ids];
        }

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                -> where($this -> whereType)
                -> where($whereRep)
                ->where($whereQues)
                ->where($where)
                ->order($sort, $order)
                ->group('student_id')
                ->count();

            $list = $this->model
                -> where($this -> whereType)
                -> where($whereRep)
                ->where($whereQues)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->group('student_id')
                ->select();

            $list = collection($list)->toArray();


            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $allcount = (new \app\admin\model\Student()) -> where(['status'=>1])-> where($this -> whereType) -> where($whereStu) -> count();
        $reportedcount = (new \app\admin\model\QuesStudent())-> where($this -> whereType) ->where($whereQues) -> whereBetween('create_time',Time::today()) -> group('student_id') -> count();

        $notreportedallcount = $allcount - $reportedcount;

        $today = Time::today();

        $co_model = new  \app\admin\model\CollegeReport;

        $co_row = $co_model ->where(['type'=>3,'college_id'=>$this->auth->gid])-> whereTime('report_time','between',$today)->find();
        if($co_row)
            $this -> assign('exist', 1);
        else
            $this -> assign('exist', 0);
        $todayStr = date("Y-m-d H:i:s",$today[0]).' - '.date("Y-m-d H:i:s",$today[1]);
        $this -> assignConfig('today', $todayStr);
        $this -> assign('allcount',$allcount);
        $this -> assign('reportedcount',$reportedcount);
        $this -> assign('notreportedallcount',$notreportedallcount);

        return $this->view->fetch();
    }


    public function exp(){
        ini_set('memory_limit', '999M');
        $and = ' ';
        $gid = $this->auth->gid;
        //学院
        if($this->auth->gtypeid == 1){
            $and .= " and college_id = '$gid' ";
        }
        //班级
        if($this->auth->gtypeid == 3){
            $and .= " and classes_id = '$gid' ";
        }

        $create_time = input('create_time');
        if(empty($create_time)){
            $timestampArr = Time::today();
            $starttime = $timestampArr[0];
            $endtime = $timestampArr[1];

        }else{
            $timeArr = explode(' - ',$create_time);
            $starttime = strtotime($timeArr[0]);
            $endtime = strtotime($timeArr[1]);
        }

        $province = input('province');
        $city = input('city');
         $nickname = input('nickname');


        if(!empty($starttime)){
            $and .= " and create_time >='$starttime' ";
        }
        if(!empty($endtime)){
            $and .= " and create_time <= '$endtime' " ;
        }

        if(!empty($province)){
            $and .= " and province='$province' ";
        }
        if(!empty($city)){
            $and .= " and city='$city' ";
        }
        if(!empty($nickname)){
            $and .= " and nickname like '$nickname' ";
        }
        if($this -> whereType){
            $and .= " and type=".$this -> whereType['type'];
        }


        $and .=" and classes_id <> 0";

        if (input('?title') && input('?answer'))
        {
            $title = input('title');
            $answer = input('answer');
            $and .= " and $title = '$answer' ";
        }

//        $sql = "select nickname,tel,sid,classes_name,college_name,year_,province,city,district, wx_formatted_address,
//            case a_1 when '0' then '无情况'  when '1' then '途径武汉' when '2' then '途径湖北(除武汉)' when '3' then '居住武汉' when '4' then '居住湖北(除武汉)' when '5' then '接触武汉籍人员'  when '6' then '接触湖北(除武汉)籍人员' when '7' then '从外省返鲁' else '-' end a_1,
//            case a_1_1 when 0 then '无' else from_unixtime(a_1_1, '%Y-%m-%d') end a_1_1,
//            case a_2 when '0' then '无情况'  when '1' then '接触确诊病历' when '2' then '接触疑似病历' else '-' end a_2,
//            case a_2_1 when 0 then '无' else from_unixtime(a_2_1, '%Y-%m-%d') end a_2_1,
//            case a_3 when '0' then '无' when '1' then '医院隔离' when '2' then '当地指定点隔离' when '3' then '居家隔离' else '-' end a_3,
//            case a_3_1 when 0 then '无' else from_unixtime(a_3_1, '%Y-%m-%d') end a_3_1,
//            case a_3_2 when '0' then '否' when '1' then '是' else '-' end a_3_2,
//            case a_4 when '0' then '健康'  when '1' then '咳嗽' when '2' then '发烧' when '3' then '呼吸困难等' when '4' then '确诊病历' when '5' then '疑似病历'  when '6' then '其它' else '-' end a_4,
//            a_4_1,
//            case a_5 when '0' then '无情况'  when '1' then '接触确诊病历' when '2' then '接触疑似病历' when '3' then '确诊病历' when '4' then '疑似病历' else '-' end a_5,
//            case a_5_1 when 0 then '无' else from_unixtime(a_5_1, '%Y-%m-%d') end a_5_1,
//            case create_time when 0 then '无' else from_unixtime(create_time, '%Y-%m-%d') end create_time
//            from qa_ques_student where 1=1  $and";
//        $rows = Db::query($sql);
        $rows = (new \app\admin\model\QuesStudent()) -> where("1=1 $and") -> select();

        $fp = fopen('php://output', 'a+');
        header("Content-Type:application/vnd.ms-excel;charset=utf-8");
        header("Content-Disposition:filename=学生上报数据导出.csv");

        $title = array('序号','姓名','手机号','学号','专业班级','学院名称','年级','省份','城市',
            '区县','微信定位地址','是否有下列情况','填写时间','接触相关人员情况','接触病例时间','所在社区（村居）21天内发生疫情',
            '如果发生过疫情,请填写时间','近14天之内您是否有下列症状未痊愈','身体状况说明','14天内本人或家庭成员有疫情重点地区（包括境外、国内外中高风险地区等）旅行史和接触史？','如果发生过上述情况,请填写时间','近14天有发热等症状未痊愈者','体温范围','上报日期','异常情况说明','备注');
        foreach($title as $k => $v) {
            $title[$k] = iconv('UTF-8', 'GBK', $v);
        }

        fputcsv($fp, $title);

        $i = 1;
        foreach($rows as $val){
           $row[0] = iconv('UTF-8', 'GBK', $i++);
            $row[1] = iconv('UTF-8', 'GBK', trim($val['nickname']));
//            $row[2] = iconv('UTF-8', 'GBK', trim($val['tel']));
            $row[2] = mb_convert_encoding(trim($val['tel']), 'GBK', 'UTF-8');

            $row[3] = iconv('UTF-8', 'GBK', trim($val['sid']));
            $row[4] = iconv('UTF-8', 'GBK', trim($val['classes_name']));
            $row[5] = iconv('UTF-8', 'GBK', trim($val['college_name']));
            $row[6] = iconv('UTF-8', 'GBK', trim($val['year_']));
            $row[7] = mb_convert_encoding(trim($val['province']), 'GBK', 'UTF-8');
            $row[8] = mb_convert_encoding(trim($val['city']), 'GBK','UTF-8' );
            $row[9] = mb_convert_encoding(trim($val['district']), 'GBK','UTF-8');
            $row[10] = mb_convert_encoding(trim($val['wx_formatted_address']), 'GBK','UTF-8' );
            $row[11] = mb_convert_encoding(trim($val['a_1_text']),'GBK', 'UTF-8');
            $row[12] = mb_convert_encoding(trim($val['a_1_1_text']), 'GBK', 'UTF-8');
            $row[13] = mb_convert_encoding(trim($val['a_2_text']), 'GBK','UTF-8' );
            $row[14] = mb_convert_encoding(trim($val['a_2_1_text']),'GBK', 'UTF-8');
            $row[15] = mb_convert_encoding(trim($val['a_3_text']), 'GBK','UTF-8');
            $row[16] = mb_convert_encoding( trim($val['a_3_1_text']), 'GBK','UTF-8');
            $row[18] = mb_convert_encoding( trim($val['a_4_text']), 'GBK','UTF-8');
            $row[19] = mb_convert_encoding( trim($val['a_4_1']), 'GBK','UTF-8'); //身体状况说明
            $row[20] = mb_convert_encoding(trim($val['a_11_text']),'GBK','UTF-8' );//14天内本人或家庭成员有疫情重点地区（包括境外、国内外中高风险地区等）旅行史和接触史？
            $row[21] = mb_convert_encoding(trim($val['a_11_1_text']), 'GBK','UTF-8' );//时间
            $row[22] = mb_convert_encoding(trim($val['a_12_text']), 'GBK','UTF-8' );//近14天有发热等症状未痊愈者
            $row[23] = iconv('UTF-8', 'GBK', $val['a_9_text']);//体温范围

            $row[24] = iconv('UTF-8', 'GBK', $val['create_time_text']);//异常情况说明
            $row[25] = mb_convert_encoding($val['info'], 'GBK','UTF-8' );//备注
            $row[26] = mb_convert_encoding($val['memo'], 'GBK','UTF-8' );


            fputcsv($fp, $row);
        }

        ob_flush();
        flush();

    }



}
